"use client"
import { batchDeleteAdminHouseholdApi, deleteAdminHouseholdApi, getHouseholdListApi } from '@/apis/household'
import { SearchOutlined } from '@ant-design/icons'
import { Button, Col, Divider, Input, message, Popconfirm, Row, Space, Table, Typography, Upload } from 'antd'
import React, { useEffect, useState } from 'react'
import ResidentDetailsModal from '@/components/ResidentDetailsModal'
import ResidentAddModal from '@/components/ResidentAddModal'
// 导入表格组件
import TableCom from '@/components/Table'

export default function Resident() {
  // 带查询的居民姓名关键字
  const [kw, setKw] = useState('')
  // 当前加载到哪也的数据
  const [pageNumber, setPageNumber] = useState(0)
  // 符合查询条件记录的总数
  const [pageCount, setPageCount] = useState(9999)
  // 当前加载到的数据
  const [residentList, setResidentList] = useState([])
  // 当前是否正在加载中
  const [loading, setLoading] = useState(false)

  const [recordCount, setRecordCount] = useState(0)
  const [pageSize, setPageSize] = useState(0)

  // 用户信息弹出框
  const [showResidentDetailsModal, setShowResidentDetailsModal] = useState(false)
  // 添加/修改信息弹窗框
  const [showResidentChangeModal, setShowResidentChangeModal] = useState(false)
  // 添加/修改弹出框模式
  const [residentChangeModalMode, setResidentChangeModalMode] = useState('add')
  // 修改成功
  const [successChange, setSuccessChange] = useState(false)

  // 要传递的居民编号
  const [hid, setHid] = useState('')

  // 选中的居民编号
  const [selectedRowKeys, setSelectedRowKeys] = useState([])

  const lodaData = async (pno) => {  // pno表示要加载的页号
    // 1.如果当前正在加载中或没有更多数据则退出
    if (loading || pno > (pageCount || 9999)) return
    // 2.设置"正在加载中"为真
    setLoading(true)
    // 3.异步请求服务器数据
    const res = await getHouseholdListApi(pno, kw)
    const resObj = await res.json()
    console.log(resObj)
    setPageCount(resObj.pageCount)
    setPageNumber(resObj.pageNum)
    setPageSize(resObj.pageSize)
    setRecordCount(resObj.recordCount)
    setResidentList(resObj.data.map((item, index) => ({
      ...item,
      key: item.hid
    })))
    // 4.设置”正在加载中“为假
    setLoading(false)

  }

  // 分页查询方法调用情形1: 组件挂载时
  useEffect(() => {
    lodaData()
  }, [])

  // 删除单个用户信息时触发
  const deleteResident = async (hid) => {
    const res = await deleteAdminHouseholdApi(hid)
    await res.json()
    lodaData(pageNumber)
  }

  // 批量删除
  const deleteAll = async () => {
    console.log(1);

    const res = await batchDeleteAdminHouseholdApi(selectedRowKeys)
    const resObj = await res.json()
    console.log(resObj);

    lodaData(pageNumber)
  }

  const handleChange = (info) => {
    console.log(info);
  }

  // 表格列定义
  const columns = [
    {
      title: '序号',
      dataIndex: 'hid',
      key: 'key',
    },
    {
      title: '编号',
      dataIndex: 'householdId',
      key: 'id',
    },
    {
      title: '姓名',
      dataIndex: 'householdName',
      key: 'name',
    },
    {
      title: '性别',
      dataIndex: 'gender',
      key: 'gender',
      render: gender => gender === <span>{'1' ? '男' : '女'}</span>
    },
    {
      title: '电话',
      dataIndex: 'phone',
      key: 'gender',
    },
    {
      title: '住址',
      dataIndex: 'householdAddr',
      key: 'address',
    },
    {
      title: '操作',
      dataIndex: 'hid',
      key: 'operation',
      render: hid => (
        <Space size={'small'}>
          <Button size='small' onClick={() => {
            setHid(hid)
            setShowResidentDetailsModal(true)
          }} type=''>详情</Button>
          <Button size='small' onClick={() => {
            setHid(hid)
            setResidentChangeModalMode('change')
            setShowResidentChangeModal(true)
          }} type=''>编辑</Button>
          <Popconfirm
            title="提示"
            description="删除操作不可撤销!您确认吗？"
            okText='确认'
            cancelText='放弃'
            onConfirm={() => deleteResident(hid)}
          >
            <Button size='small' danger type=''>删除</Button>
          </Popconfirm>
        </Space>
      )
    },
  ]

  // 分页信息
  const pagination = {
    current: pageNumber,
    defaultCurrent: 1,
    position: ['bottomRight'],
    total: recordCount,
    defaultPageSize: 10,
    pageSize: pageSize,
    showSizeChanger: false,
    onChange: e => lodaData(e)
  }
  return (
    <div style={{ padding: '10px' }}>
      <Typography.Title level={3}>居民信息</Typography.Title>
      <Divider style={{ margin: '5px 0 10px', borderColor: '#7cb305', }}></Divider>
      <Row>
        <Col style={{ flex: 1 }}>
          <Space.Compact>
            <Button onClick={() => {
              setResidentChangeModalMode('add')
              setShowResidentChangeModal(true)
            }}>添加新的</Button>
            <Button onClick={deleteAll}>批量删除</Button>
            <Upload onChange={handleChange} headers={{token: localStorage.getItem('adminToken')}} name='residents' action='https://www.codeboy.com/zhsqapi/admin/household/batch/add' method='post' showUploadList={false} beforeUpload={(file) => {
              const isJpgOrPng = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
              if (!isJpgOrPng) {
                message.error('只能上传xlsx格式的文件');
              }
              return isJpgOrPng
            }}>
              <Button>批量导入</Button>
            </Upload>

            <Button>导出选中</Button>
            <Button>导出所有</Button>
          </Space.Compact>
        </Col>
        <Col>
          <Space.Compact>
            <Input onPressEnter={() => {
              lodaData(1, kw)
              setPageNumber(1)
            }} placeholder='输入姓名关键字' onChange={(e) => setKw(e.target.value)}></Input>
            <Button icon={<SearchOutlined />} onClick={() => {
              // if(!kw) return 
              lodaData(1, kw)
              setPageNumber(1)
            }} />
          </Space.Compact>
        </Col>
      </Row>
      {/* 表格，分页条 */}
      <Table style={{ marginTop: '10px' }} rowSelection={{
        onChange: (e) => setSelectedRowKeys(e)
      }}
        pagination={{
          current: pageNumber,
          defaultCurrent: 1,
          position: ['bottomRight'],
          total: recordCount,
          // defaultPageSize: 10
          pageSize: pageSize,
          showSizeChanger: false,
          onChange: e => lodaData(e)
        }}
        loading={loading}
        columns={[
          {
            title: '序号',
            dataIndex: 'hid',
            key: 'key',
          },
          {
            title: '编号',
            dataIndex: 'householdId',
            key: 'id',
          },
          {
            title: '姓名',
            dataIndex: 'householdName',
            key: 'name',
          },
          {
            title: '性别',
            dataIndex: 'gender',
            key: 'gender',
            render: gender => gender === <span>{'1' ? '男' : '女'}</span>
          },
          {
            title: '电话',
            dataIndex: 'phone',
            key: 'gender',
          },
          {
            title: '住址',
            dataIndex: 'householdAddr',
            key: 'address',
          },
          {
            title: '操作',
            dataIndex: 'hid',
            key: 'operation',
            render: hid => (
              <Space size={'small'}>
                <Button size='small' onClick={() => {
                  setHid(hid)
                  setShowResidentDetailsModal(true)
                }} type=''>详情</Button>
                <Button size='small' onClick={() => {
                  setHid(hid)
                  setResidentChangeModalMode('change')
                  setShowResidentChangeModal(true)
                }} type=''>编辑</Button>
                <Popconfirm
                  title="提示"
                  description="删除操作不可撤销!您确认吗？"
                  okText='确认'
                  cancelText='放弃'
                  onConfirm={() => deleteResident(hid)}
                >
                  <Button size='small' danger type=''>删除</Button>
                </Popconfirm>
              </Space>
            )
          },
        ]} dataSource={residentList}></Table>
      <TableCom residentList={residentList} columns={columns} pagination={pagination} loading={loading}/>
      <ResidentDetailsModal successChange={successChange} hid={hid} isOpen={showResidentDetailsModal} setIsOpen={() => setShowResidentDetailsModal(false)} />
      <ResidentAddModal setSuccessChange={() => setSuccessChange(!successChange)} pageNumber={pageNumber} lodaData={lodaData} mode={residentChangeModalMode} hid={hid} isOpen={showResidentChangeModal} setIsOpen={() => setShowResidentChangeModal(false)} />
    </div>
  )
}
